package com.pagepub.expo.action.web;

import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;

import java.util.Iterator;

import java.util.HashMap;
import java.util.Iterator;

import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jspsmart.upload.smartUpload.SmartUpload;
import com.jspsmart.upload.smartUpload.SmartUploadException;
import com.pagepub.comm.util.FormatDateTime;
import com.pagepub.core.ftp.ImgDeal;
import com.pagepub.core.ftp.UploadXml;
import com.pagepub.core.utils.Config;
import com.pagepub.core.utils.ExtendString;
import com.pagepub.core.utils.StringUtil;
import com.pagepub.expo.entity.CorpCommpany;
import com.pagepub.expo.entity.CorpPublication;
import com.pagepub.expo.entity.CorpPublicationPage;
import com.pagepub.expo.manager.AppSeqMng;
import com.pagepub.expo.manager.CorpCommpanyMng;
import com.pagepub.expo.manager.CorpPublicationMng;
import com.pagepub.expo.manager.CorpPublicationPageMng;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

public class BatchUploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public BatchUploadServlet() {
		super();
	}

	public static final String FILE_SEPARATOR = System.getProperties()
			.getProperty("file.separator");

	private ServletConfig config;

	final public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}

	final public ServletConfig getServletConfig() {
		return config;
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		// out.println("<html>");
		// out.println("<head>");
		out
				.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", -1000);
		out.println("<title>上传图片</title>");
		out.println("</head>");
		out.println("<body bgcolor='white'>");
		out.print(" This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}

	public void doPost1(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		String tempFilepath = "D:\\uptemp\\";
		String savepath = "D:\\upload\\";
		// 如果没有临时目录，则创建它
		if (!(new File(tempFilepath).isDirectory())) {
			try {
				new File(tempFilepath).mkdirs();
			} catch (SecurityException e) {
				System.out.println("can   not   make   security   direcoty");
			}
		}

		// 如果没有上传目的目录，则创建它
		if (!(new File(savepath).isDirectory())) {
			try {
				new File(savepath).mkdirs();
			} catch (SecurityException e) {
				System.out.println("can   not   make   security   direcoty");
			}
		}

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart) {
			System.out.println("表单数据格式不是multipart/form-data，或者非法提交");
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// factory.setRepository(tempFilepath);
		ServletFileUpload upload = new ServletFileUpload(factory);// 创建文件上传对象

		// upload.setSizeThreshold(4096); //
		upload.setSizeMax(2621440); // 最大允许上传2.5M的文件
		// upload.setRepositoryPath(tempFilepath);

		String s = DiskFileUpload.FORM_DATA;
		System.out.println(s);
		try{
		List uploadlist = upload.parseRequest(request);
		Iterator iter = uploadlist.iterator();

		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (!item.isFormField()) {
				String filename = item.getName();

				filename = filename.substring(filename.lastIndexOf("\\") + 1);// 从全路径中提取文件名
				// filename=FilenameUtils.getName(filename);
				// out.println(name);
				long size = item.getSize();
				if ((filename == null) || filename.equals("") && size == 0)
					continue;
				savepath = savepath + filename;
				// System.out.println("savepath   is   "+savepath);
				File saveFilepath = new File(savepath);
				item.write(saveFilepath);
			}
		}}catch(Exception e){
			e.printStackTrace();
		}
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		out.println("errorcode=ok");
		// out.println("</body>");
		// out.println("</html>");
		out.flush();
		out.close();
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		// out.println("<html>");
		// out.println("<head>");
		// out
		// .println("<meta http-equiv=\"Content-Type\" content=\"text/html;
		// charset=UTF-8\">");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		int maxSize = 1024 * 1024 * 1024 * 30; // 1.限制每个上传文件的最大长度。2M
		int maxFileSize = 2000000000; // 限制总上传数据的长度
		String UpType = "jpg,gif,png,bmp,swf,SWF,JPG,GIF,PNG,BMP";
		try {
			SmartUpload mySmartUpload = new SmartUpload();
			mySmartUpload.initialize(config, request, response);// 上传初始化

			mySmartUpload.setMaxFileSize(maxSize);// 1.限制每个上传文件的最大长度

			mySmartUpload.setTotalMaxFileSize(maxFileSize);// 2.限制总上传数据的长度
			mySmartUpload.setAllowedFilesList(UpType);// 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件

			mySmartUpload.setCharset("UTF-8");
			mySmartUpload.upload();
			if (mySmartUpload.getFiles().getSize() > 0) {
				try {
					com.jspsmart.upload.smartUpload.SmartFile myFile = null;

					for (int j = 0; j < mySmartUpload.getFiles().getCount(); j++) {
						
					}
				} catch (Exception ex) {
					out.println(ex.getMessage());
				}

			} else {
				out.println("errorcode=没有或上传电子书规格不正确!");
			}

		} catch (Exception e) {
			out.println(e.getMessage());
			e.printStackTrace();
		}
//		File tempPath = new File("E:\\tmp");//上传文件目录
//		File uploadPath = new File("E:\\upload");//上传文件目录
//
//		DiskFileItemFactory factory = new DiskFileItemFactory();
//		factory.setSizeThreshold(4096*1024); // 设置缓冲区大小，这里是4kb
//	 factory.setRepository(tempPath);//设置缓冲区目录
//
//	 ServletFileUpload upload = new ServletFileUpload(factory);
//	// Set overall request size constraint
//	 upload.setSizeMax(4194304*10); // 设置最大文件尺寸，这里是4MB
//	 try{
//	 List<FileItem> items = upload.parseRequest(request);//得到所有的文件
//	 Iterator<FileItem> i = items.iterator();
//	 
//	 while (i.hasNext()) {
//		 FileItem fi = (FileItem) i.next();
//		 String fileName = fi.getName();
//		 if (fileName != null) {
//			 File fullFile = new File(fi.getName());
//			 File savedFile = new File(uploadPath, fullFile.getName());
//			 	fi.write(savedFile);
//		}
//	 }}
//	 catch(Exception e){
//		 e.printStackTrace();
//	 }
		out.println("errorcode=ok");
		out.flush();
		out.close();
	}
}
	